package org.flowable.ui.common.security;

import com.jeeplus.sys.service.dto.UserDTO;
import com.jeeplus.sys.utils.UserUtils;
import org.flowable.common.engine.api.FlowableIllegalStateException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import java.util.Set;

/**
 * 重写flowable 6.7.2版权权限
 */
public class SecurityUtils {

    static final String GROUP_PREFIX = "GROUP_";
    static final String TENANT_PREFIX = "TENANT_";
    private static SecurityScopeProvider securityScopeProvider = new FlowableSecurityScopeProvider ( );

    private SecurityUtils() {
    }

    public static GrantedAuthority createTenantAuthority(String tenantId) {
        return new SimpleGrantedAuthority ( "TENANT_" + tenantId );
    }

    public static GrantedAuthority createGroupAuthority(String groupId) {
        return new SimpleGrantedAuthority ( "GROUP_" + groupId );
    }

    public static void setSecurityScopeProvider(SecurityScopeProvider securityScopeProvider) {
        securityScopeProvider = securityScopeProvider;
    }

    public static String getCurrentUserId() {
        SecurityScope user = getCurrentSecurityScope ( );
        return user != null ? user.getUserId ( ) : null;
    }

    public static SecurityScope getCurrentSecurityScope() {
        UserDTO userDTO = UserUtils.getCurrentUserDTO ();
        SecurityScope securityScope = new SecurityScope ( ) {
            @Override
            public String getUserId() {
                return userDTO.getId ( );
            }

            @Override
            public Set <String> getGroupIds() {
                return null;
            }

            @Override
            public String getTenantId() {
                return null;
            }

            @Override
            public boolean hasAuthority(String s) {
                return false;
            }
        };
        return securityScope;
    }

    public static SecurityScope getSecurityScope(Authentication authentication) {
        return securityScopeProvider.getSecurityScope ( authentication );
    }

    public static SecurityScope getAuthenticatedSecurityScope() {
        SecurityScope currentSecurityScope = getCurrentSecurityScope ( );
        if ( currentSecurityScope != null ) {
            return currentSecurityScope;
        } else {
            throw new FlowableIllegalStateException ( "User is not authenticated" );
        }
    }
}
